package com.enation.app.javashop.buyer.api.member;


import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.vo.DistributionMissionVO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.distribution.service.DistributionMissionService;
import com.enation.app.javashop.core.member.MemberErrorCode;
import com.enation.app.javashop.core.member.model.dos.LeaderDO;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dto.MemberEditDTO;
import com.enation.app.javashop.core.member.model.dto.MemberStatisticsDTO;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.activitymessage.model.vo.ActivityMessageRecordVO;
import com.enation.app.javashop.core.promotion.activitymessage.service.ActivityMessageManager;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.DistributionFansOrderVO;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.OrderProfitStatisticVO;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.trade.order.model.dos.OrderMemberDO;
import com.enation.app.javashop.core.trade.order.model.dto.OrderProfitQueryParam;
import com.enation.app.javashop.core.trade.order.model.enums.YesOrNoEnums;
import com.enation.app.javashop.core.trade.order.service.OrderMemberManager;
import com.enation.app.javashop.core.trade.order.service.OrderProfitManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.exception.ResourceNotFoundException;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Buyer;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 会员控制器
 *
 * @author zh
 * @version v2.0
 * @since v7.0.0
 * 2018-03-16 11:33:56
 */
@Slf4j
@RestController
@RequestMapping("/members")
@Api(description = "会员相关API")
public class MemberBuyerController {

    @Autowired
    private OrderMemberManager orderMemberManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private Cache cache;
    @Autowired
    private LeaderManager leaderManager;
    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private OrderProfitManager orderProfitManager;
    @Autowired
    private ActivityMessageManager activityMessageManager;
    @Autowired
    private ShopManager shopManager;
    @Autowired
    private DistributionMissionService distributionMissionService;

    /**
     * 日志记录
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @PutMapping
    @ApiOperation(value = "完善会员细信息", response = Member.class)
    public Member perfectInfo(@Valid MemberEditDTO memberEditDTO) {
        Buyer buyer = UserContext.getBuyer();
        Member member = memberManager.getModel(buyer.getUid());
        //判断数据库是否存在此会员
        if (member == null) {
            throw new ResourceNotFoundException("此会员不存在");
        }
        BeanUtil.copyProperties(memberEditDTO, member);
        if (memberEditDTO.getRegion() != null) {
            if (StringUtil.isEmpty(memberEditDTO.getRegion().getCounty())) {
                throw new ServiceException(MemberErrorCode.E141.code(), "地区不合法");
            }
            BeanUtil.copyProperties(memberEditDTO.getRegion(), member);
        }
        //判断会员是修改资料还是完善资料
        if (member.getInfoFull() != null && !member.getInfoFull().equals(1)) {
            member.setInfoFull(1);
            this.amqpTemplate.convertAndSend(AmqpExchange.MEMBER_INFO_COMPLETE, "member-info-complete-routingkey", member.getMemberId());
        }
        member.setFace(memberEditDTO.getFace());
        member.setTel(memberEditDTO.getTel());
        member.setLat(memberEditDTO.getLat());
        member.setLng(memberEditDTO.getLng());
        this.memberManager.edit(member, buyer.getUid());
        //发送会员资料变化消息
        this.amqpTemplate.convertAndSend(AmqpExchange.MEMBER_INFO_CHANGE, AmqpExchange.MEMBER_INFO_CHANGE + "_ROUTING", member.getMemberId());
        return member;
    }


    @GetMapping
    @ApiOperation(value = "查询当前会员信息")
    public Member get() {
        return this.memberManager.getModel(UserContext.getBuyer().getUid());
    }


    @GetMapping("/get-all")
    @ApiOperation(value = "查询当前会员所有信息")
    public Map getAll() {
        Member member = this.memberManager.getModel(UserContext.getBuyer().getUid());
        LeaderDO leaderDO = leaderManager.getByMemberId(member.getMemberId());
        DistributionDO distributor = distributionManager.getDistributorByMemberId(member.getMemberId());
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("member" , member);
        resultMap.put("leader" , leaderDO);
        resultMap.put("distributor", distributor);
        return resultMap;
    }


    @ApiOperation(value = "注销会员登录")
    @PostMapping(value = "/logout")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "会员id", dataType = "int", paramType = "query", required = true)
    })
    public String loginOut(@NotNull(message = "会员id不能为空") Integer uid) {
        this.memberManager.logout(uid);
        return null;
    }

    @GetMapping("/statistics")
    @ApiOperation(value = "统计当前会员的一些数据")
    public MemberStatisticsDTO getMemberStatistics() {
        return this.memberManager.getMemberStatistics();
    }



    @ApiOperation(value = "'个人中心'内容汇总查询")
    @GetMapping(value = "/my-view")
    public Map<String, Object> myView() {
        Buyer buyer = UserContext.getBuyer();
        Integer memberId = buyer.getUid();

        Object o = cache.get("LOGOUT" + memberId);
        if(o != null && "1".equals(o.toString())){
            cache.remove("LOGOUT" + memberId);
            throw new ServiceException("403", "会员登录信息已过期");
        }

        // 查询订单提醒
        OrderMemberDO orderMember = orderMemberManager.getOrderMember(memberId);
        if (orderMember == null) {
            orderMemberManager.orderStatistic(memberId);
            orderMember = orderMemberManager.getOrderMember(memberId);
        }
        OrderProfitStatisticVO dayOrderProfitStatisticVO = null;
        OrderProfitStatisticVO monthOrderProfitStatisticVO = null;
        Date date = new Date();
        // 查询今日销售，今日提成
        OrderProfitQueryParam queryParam = new OrderProfitQueryParam();
        queryParam.setMemberId(memberId);
        queryParam.setStartTime(DateUtil.loadDayBegin(date));
        queryParam.setEndTime(DateUtil.loadDayBegin(date)+86400);
        dayOrderProfitStatisticVO = orderProfitManager.statisticAll(queryParam);
        dayOrderProfitStatisticVO.show();
        // 查询本月销售，本月提成
        queryParam.setStartTime(DateUtil.loadMonthBegin(date));
        queryParam.setEndTime(DateUtil.loadMonthBegin(date)+2678400);
        monthOrderProfitStatisticVO = orderProfitManager.statisticAll(queryParam);
        monthOrderProfitStatisticVO.show();

        // 查询粉丝下单情况
        List<DistributionFansOrderVO> distributionFansOrderVOList = distributionManager.getDistributionFansOrderList(memberId);

        // 如果是启用中的团长，查询最新的团长任务
        DistributionMissionVO distributionMission = null;
        DistributionDO distributionDO = distributionManager.getDistributorByMemberId(memberId);
        if (distributionDO != null && distributionDO.getStatus() == YesOrNoEnums.YES.getIndex() && distributionDO.getAuditStatus() == 2) {
            distributionMission = distributionMissionService.queryLatestMission();
        }

        // 封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("prompt", orderMember);
        resultMap.put("dayStatistic", dayOrderProfitStatisticVO);
        resultMap.put("monthStatistic", monthOrderProfitStatisticVO);
        resultMap.put("fansData", distributionFansOrderVOList);
        resultMap.put("distributionMission",distributionMission);
        return resultMap;
    }


    @GetMapping("/activity_subscription")
    @ApiOperation(value = "会员 活动订阅")
    public void  activitySubscription(ActivityMessageRecordVO activityMessageRecordVO){
        activityMessageManager.addActivityMessageRecordVO(activityMessageRecordVO);
    }




}